// 根据指定班级，获取该班级信息以及学生与老师的列表
import express from 'express';
import pool from "../importantApi/db_connection.js";

const router = express.Router();
router.get('/', async (req, res) => {
    const {classId} = req.query;
    if (!classId) {
        return res.status(401).json({
            code: 401,
            msg: "缺少必要参数"
        })
    }
    try {
        // 查询班级信息和管理员
        const classQuery = `
            SELECT c.class_id,
                   c.class_name,
                   u.user_id   AS manager_id,
                   u.user_name AS manager_name
            FROM classinfo c
                     JOIN userinfo u ON c.user_id = u.user_id
            WHERE c.class_id = ?;
        `;

        // 查询班级成员列表（老师和学生）
        const membersQuery = `
            SELECT u.user_id,
                   u.user_name,
                   u.identity,
                   CASE WHEN u.user_id = c.user_id THEN 1 ELSE 0 END AS is_manager
            FROM user_class uc
                     JOIN userinfo u ON uc.user_id = u.user_id
                     JOIN classinfo c ON uc.class_id = c.class_id
            WHERE uc.class_id = ?
              AND u.identity IN ('teacher', 'student');
        `;
        try {
            // 并行查询
            const [classResult, membersResult] = await Promise.all([
                pool.query(classQuery, [classId]),
                pool.query(membersQuery, [classId])
            ]);
            // 处理结果
            const classInfo = classResult[0]?.[0] || null;  // 班级信息（假设查询结果非空）
            const members = membersResult[0];     // 成员列表
            // 分身
            const teachers = members.filter(item => item.identity === 'teacher');
            const students = members.filter(item => item.identity === 'student');

            return res.status(200).json({
                code: 200,
                data: {
                    classInfo,
                    teachers,
                    students
                }
            })
        } catch (err) {
            console.log(err)
            return res.status(500).json({
                code: 500,
                error: err,
                msg: "查询错误"
            })
        }

    } catch (err) {
        console.log(err)
        return res.status(500).json({
            code: 500,
            error: err,
            msg: "查询错误"
        })
    }
})
export default router;